#include <stdio.h>
#include <string.h>
//#include <malloc.h>
#include <stdlib.h>

#include "circularbuf.h"

#define DEBUG 0
#if DEBUG
#define PRINTF(...) printf(__VA_ARGS__)
#else
#define PRINTF(...)
#endif


/*
 * Circular Buffer Example
 * Take it from http://en.wikipedia.org/wiki/Circular_buffer
 */


/* Init Circular Buffer */
CircularBuffer* CircularBufferInit(CircularBuffer** pQue, int size)
{
        int sz = size*sizeof(msg_to_sink)+sizeof(CircularBuffer);
        *pQue = (CircularBuffer*) malloc(sz);
        if(*pQue)
        {
            PRINTF("Init CircularBuffer: keys[%d] (%d)\n", size, sz);
            (*pQue)->size=size;
            (*pQue)->writePointer = 0;
            (*pQue)->readPointer  = 0;
            (*pQue)->count = 0;
        }
        return *pQue;
}

static int CircularBufferIsFull(CircularBuffer* que)
{
     return (que->count == que->size);
}

static int CircularBufferIsEmpty(CircularBuffer* que)
{
     return (que->count == 0);
}

int CircularBufferEnque(CircularBuffer* que, msg_to_sink k)
{
        int isFull = CircularBufferIsFull(que);
        if (isFull){
            PRINTF("isFull\n");
        } else {
            que->keys[que->writePointer] = k;
            que->writePointer++;
            que->writePointer %= que->size;
            que->count++;
        }
        return isFull;
}

int CircularBufferDeque(CircularBuffer* que, msg_to_sink* pK)
{
        int isEmpty =  CircularBufferIsEmpty(que);
        if (isEmpty){
            PRINTF("isEmpty\n");
        } else {
            *pK = que->keys[que->readPointer];
            que->readPointer++;
            que->readPointer %= que->size;
            que->count--;
        }
        return(isEmpty);
}
